package com.spzx.order.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.domain.*;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.vo.ProductSku;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.system.api.RemoteUserService;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.api.domain.UserAddress;
import io.jsonwebtoken.lang.Assert;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.service.IOrderInfoService;

/**
 * 订单Service业务层处理
 *
 * @author atguigu
 * @date 2024-10-01
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService
{
    @Resource
    OrderInfoMapper orderInfoMapper;
    @Resource
    OrderItemMapper orderItemMapper;
    @Resource
    OrderLogMapper orderLogMapper;
    @Resource
    RemoteCartService remoteCartService;
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    RemoteProductService remoteProductService;
    @Resource
    RemoteUserService remoteUserService;
    @Resource
    RemoteUserAddressService remoteUserAddressService;
    @Resource
    RabbitService rabbitService;

    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo)
    {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    @Override
    public TradeVo orderTradeData() {
        Long userId = SecurityContextHolder.getUserId();
        List<CartInfo> cartInfos = remoteCartService.getCartCheckedList(userId, SecurityConstants.INNER).getData();
        List<OrderItem> orderItemList = cartInfos.stream().map(cartInfo -> {
            OrderItem orderItem = new OrderItem();
            orderItem.setSkuNum(cartInfo.getSkuNum());
            orderItem.setSkuId(cartInfo.getSkuId());
            orderItem.setThumbImg(cartInfo.getThumbImg());
            orderItem.setSkuName(cartInfo.getSkuName());
            orderItem.setSkuPrice(cartInfo.getSkuPrice());
            return orderItem;
        }).collect(Collectors.toList());
        TradeVo tradeVo = new TradeVo();
        BigDecimal bigDecimal = new BigDecimal("0");
        for (OrderItem orderItem:orderItemList) {
            bigDecimal.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        tradeVo.setTotalAmount(bigDecimal);
        tradeVo.setOrderItemList(orderItemList);
        String TRADENO =generateTradeNo(userId);
        tradeVo.setTradeNo(TRADENO);
        return tradeVo;
    }

    @Override
    public Long submitOrder(OrderForm orderForm) {
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        String tradeNo = orderForm.getTradeNo();
        Long userId = SecurityContextHolder.getUserId();
        Long userAddressId = orderForm.getUserAddressId();
        Boolean b = checkTreadeNo(tradeNo);
        Assert.isTrue(b,"交易号失败");
        redisTemplate.delete(tradeNo);
        List<Long> skuIds = new ArrayList<>();
        skuIds= orderItemList.stream().map(orderItem -> {
            return orderItem.getSkuId();
        }).collect(Collectors.toList());
        List<SkuPrice> skuPrices = remoteProductService.getSkuPriceList(skuIds, SecurityConstants.INNER).getData();
        Map<Long, BigDecimal> skuPricesMap = skuPrices.stream().collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));
        for(OrderItem orderItem :orderItemList){
            int i = orderItem.getSkuPrice().compareTo(skuPricesMap.get(orderItem.getSkuPrice()));
            if (i!=0){
                remoteCartService.updateCartPrice(userId, SecurityConstants.INNER);
                throw new RuntimeException("实时价格校验失败");
            }
        }
        //校验并保存
        List<SkuLockVo> skuLockVos = orderItemList.stream().map(orderItem -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            skuLockVo.setSkuId(orderItem.getSkuId());
            return skuLockVo;
        }).collect(Collectors.toList());
        String data = remoteProductService.checkAndLock(orderForm.getTradeNo(), skuLockVos, SecurityConstants.INNER).getData();
        Long orderId = 0L;
        // 保存订单信息
        try {
            orderId = saveOrder(orderForm);

            // 删除购物车中的选中信息
            remoteCartService.deleteCartCheckedList(userId, SecurityConstants.INNER);

            //延迟关单
//        rabbitService.sendDelayMessage(MqConst.EXCHANGE_CANCEL_ORDER, MqConst.ROUTING_CANCEL_ORDER, orderId + "");
            rabbitService.sendDelayMessage(MqConst.EXCHANGE_CANCEL_ORDER, MqConst.ROUTING_CANCEL_ORDER, orderId+"", 10000);
        } catch (Exception e) {
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_TEST, orderId);
        }

        return orderId;
    }

    @Override
    public TradeVo buy(Long skuId) {
        ProductSku productSku = remoteProductService.getProductSku(skuId, SecurityConstants.INNER).getData();
        List<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(skuId);
        orderItem.setSkuName(productSku.getSkuName());
        orderItem.setSkuNum(1);
        orderItem.setSkuPrice(productSku.getSalePrice());
        orderItem.setThumbImg(productSku.getThumbImg());
        orderItemList.add(orderItem);
        BigDecimal saleAllPrice = productSku.getSalePrice();

        String tradeNo = this.generateTradeNo(SecurityUtils.getUserId());
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(saleAllPrice);
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTradeNo(tradeNo);
        return tradeVo;
    }

    @Override
    public List<OrderInfo> selectUserOrderInfoList(Integer orderStatus) {
        Long userId = SecurityContextHolder.getUserId();
        List<OrderInfo> orderInfoList=orderInfoMapper.selectUserOrderInfoList(userId,orderStatus);
        if ( !CollectionUtils.isEmpty(orderInfoList)) {
            List<Long> orderlist = orderInfoList.stream().map(OrderInfo::getId).collect(Collectors.toList());
            List<OrderItem> orderDetailList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().in(OrderItem::getOrderId, orderlist));
            Map<Long, List<OrderItem>> orderIdToOrderItemListMap = orderDetailList.stream().collect(Collectors.groupingBy(OrderItem::getOrderId));
            orderInfoList.forEach(item -> {
                item.setOrderItemList(orderIdToOrderItemListMap.get(item.getId()));
            });

        }
        return orderInfoList;
    }

    @Override
    public void processCloseOrder(String orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if (orderInfo != null && orderInfo.getOrderStatus().intValue() == 0) {
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("未支付自动取消");
            orderInfoMapper.updateById(orderInfo);

            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1);
            orderLog.setNote("系统取消订单");
            orderLogMapper.insert(orderLog);
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.QUEUE_UNLOCK, orderInfo.getOrderNo());
        }
    }

    @Override
    public void cancelOrder(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if (orderInfo != null && orderInfo.getOrderStatus().intValue()==0) {
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("用户取消订单");
            orderInfoMapper.updateById(orderInfo);
            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1);
            orderLog.setNote("用户取消订单");
            orderLogMapper.insert(orderLog);

        }
    }

    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));
        List<OrderItem> orderItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderInfo.getId()));
        orderInfo.setOrderItemList(orderItems);
        return orderInfo;
    }

    private Long saveOrder(OrderForm orderForm) {
        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderNo(orderInfo.getOrderNo());//订单号
        orderInfo.setUserId(userId);//id
        orderInfo.setNickName(userName);//用户名
        orderInfo.setRemark(orderForm.getRemark());//备注

        //查询用户锁选择的地址
        UserAddress userAddress = remoteUserAddressService.getUserAddress(userId, SecurityConstants.INNER).getData();
        orderInfo.setReceiverName(userAddress.getName());// 地址
        orderInfo.setReceiverPhone(userAddress.getPhone());// 地址
        orderInfo.setReceiverTagName(userAddress.getTagName());// 地址
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());// 地址
        orderInfo.setReceiverCity(userAddress.getCityCode());// 地址
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());// 地址
        orderInfo.setReceiverAddress(userAddress.getFullAddress());// 地址


        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = new BigDecimal(0);// 总金额
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount);// 总金额
        orderInfo.setCouponAmount(new BigDecimal(0));// 优惠券
        orderInfo.setOriginalTotalAmount(totalAmount);// 原价
        orderInfo.setFeightFee(orderForm.getFeightFee());// 运费
        //OrderInfo类的orderStatus属性的类型改为Integer
        orderInfo.setOrderStatus(0);// 订单状态，0-未支付
        orderInfoMapper.insert(orderInfo);

        //保存订单明细
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItemMapper.insert(orderItem);// 订单详情
        }

        //记录日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLogMapper.insert(orderLog);
        return orderInfo.getId();
    }

    private Boolean checkTreadeNo(String tradeNo) {
        Long userId = SecurityContextHolder.getUserId();
        String userTradeKey = "user:tradeNo:" + userId;
        String tradeNoCache = (String)redisTemplate.opsForValue().get(userTradeKey);

        return tradeNo.equals(tradeNoCache);
    }

    private String generateTradeNo(Long userId) {
        //1.构建流水号Key
        String userTradeKey = "user:tradeNo:" + userId;
        //2.构建流水号value
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        //3.将流水号存入Redis 暂存5分钟
        redisTemplate.opsForValue().set(userTradeKey, tradeNo, 5, TimeUnit.MINUTES);
        return tradeNo;
    }

}
